package cc.wsyw126.java.lintCode.swap_two_nodes_in_linked_list;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @param v2   an integer
     * @return a new head of singly-linked list
     * @oaram v1 an integer
     */
    public ListNode swapNodes(ListNode head, int v1, int v2) {
        if (head == null || head.next == null)
            return head;
        ListNode root = new ListNode(0);
        root.next = head;

        ListNode pre = root, pre1 = null, head1 = head;
        ListNode pre2 = null;
        ListNode localV1 = null, localV2 = null;

        while (head1 != null) {
            if (head1.val == v1) {
                localV1 = head1;
                pre1 = pre;

            } else if (head1.val == v2) {
                localV2 = head1;
                pre2 = pre;
            }
            pre = head1;
            head1 = head1.next;
        }

        if (localV1 != null && localV2 != null) {
            if (localV1.next == localV2) {
                pre1.next = localV2;
                localV1.next = localV2.next;
                localV2.next = localV1;
            } else if (localV2.next == localV1) {
                pre2.next = localV1;
                localV2.next = localV1.next;
                localV1.next = localV2;
            } else {
                ListNode temp = localV2.next;
                pre1.next = localV2;
                localV2.next = localV1.next;
                pre2.next = localV1;
                localV1.next = temp;
            }
        }
        return root.next;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        ListNode listNode1 = new ListNode(2);
        ListNode listNode2 = new ListNode(3);
        ListNode listNode3 = new ListNode(4);
        listNode.next = listNode1;
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = null;

        Solution s = new Solution();
        ListNode listNode4 = s.swapNodes(listNode, 2, 1);
        while (listNode4 != null) {
            System.out.println("listNode4.val = " + listNode4.val);
            listNode4 = listNode4.next;
        }

    }
}